<?php
//On vérrouille la caméra correspondante dans la base.
require_once("../../config.php");
require_once("myLib.php");
global $CFG, $COURSE, $USER;

//Paramètres
$Ginstid = optional_param('instid', null, PARAM_INT);
$Guuid = optional_param('uuid', null, PARAM_SAFEDIR);
$Gcam = optional_param('cam', null, PARAM_ALPHAEXT);

//Permission
if(isset($_GET['instid'])){
    if(is_allowed('mod/podcast:edit', $COURSE->id, $Ginstid)){
        if(isset($Gcam)){

            $lockObj = new stdClass;
            $lockObj->uuid = strval($Guuid);
            $lockObj->user = strval($USER->id);

            //On test d'abord si la caméra est déjà utilisée
            if($verrou = get_record("podcast_cameras", "uuid", $Guuid)){
                if($verrou->user === $USER->id){
                    $success = "SUCCESS";
                }else{
                    $success = "FAILURE";
                    $reason = "Someone had been faster than you, this cameras s now locked.";
                }
            }else{
                if($reason = insert_record("podcast_cameras", $lockObj, true)){
                    $success = "SUCCESS";
                }else{
                    $success = "FAILURE";
                }
            }
        }
    }else{
        $success = "FAILURE";
        $reason = "Permission denied.";
    }
}else{
    $success = "FAILURE";
    $reason = "Permission denied.";
}
header('Content-Type: text/xml; charset=UTF-8');
//On rend compte au client du succès ou de l'échec de l'opération.
$doc = new DOMDocument('1.0', 'utf-8');
$message = $doc->createElement( "message" );
$doc->appendChild( $message );
$xmlRespSucc = $doc->createElement( "success" );
$xmlRespSuccWhy = $doc->createElement( "reason" );
$xmlRespCameraName = $doc->createElement( "cameraName" );
$xmlRespCameraUuid = $doc->createElement( "cameraUuid" );
$xmlRespCameraName->appendChild( $doc->createTextNode( $Gcam ));
$xmlRespCameraUuid->appendChild( $doc->createTextNode( $Guuid ));
$xmlRespSucc->appendChild( $doc->createTextNode( $success ));
$xmlRespSuccWhy->appendChild( $doc->createTextNode( $reason ));
$message->appendChild( $xmlRespSucc );
$message->appendChild( $xmlRespSuccWhy );
$message->appendChild( $xmlRespCameraName );
$message->appendChild( $xmlRespCameraUuid );
echo $doc->saveXML();
?>
